<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="设备名称" prop="deviceName">
        <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="在线状态" prop="onlineStatus">
        <el-select v-model="queryParams.onlineStatus" placeholder="请选择在线状态" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.YK_DEVICE_ONLINE_STATE)" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>
      <!-- <el-form-item label="设备状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.YK_DEVICE_STATE)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="最后心跳" prop="lastHeartbeatTime">
        <el-date-picker v-model="queryParams.lastHeartbeatTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>
      <el-form-item label="IP地址" prop="ipAddress">
        <el-input v-model="queryParams.ipAddress" placeholder="请输入IP地址" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="内存MB" prop="memorySize">
        <el-input v-model="queryParams.memorySize" placeholder="请输入内存大小(MB)" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="硬盘GB" prop="diskSize">
        <el-input v-model="queryParams.diskSize" placeholder="请输入硬盘大小(GB)" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>


      <el-form-item label="备注" prop="remark">
        <el-input v-model="queryParams.remark" placeholder="请输入备注" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  
  <!-- 操作按钮区域 -->
  <ContentWrap>
    <div class="flex items-center">
      <el-button type="primary" plain @click="openAddDeviceDialog" v-hasPermi="['yunkong:device-key:create']">
        <Icon icon="ep:plus" class="mr-5px" /> 添加设备
      </el-button>
      <el-button type="success" plain @click="openViewKeysDialog">
        <Icon icon="ep:key" class="mr-5px" /> 查看秘钥
      </el-button>
      <el-button type="success" plain @click="handleExport" :loading="exportLoading"
        v-hasPermi="['yunkong:device:export']">
        <Icon icon="ep:download" class="mr-5px" /> 导出
      </el-button>
      <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
        v-hasPermi="['yunkong:device:delete']">
        <Icon icon="ep:delete" class="mr-5px" /> 批量删除
      </el-button>
      <el-button type="warning" plain :disabled="isEmpty(checkedIds)" @click="() => openUpdateGroupDialog()"
        v-hasPermi="['yunkong:device:update']">
        <Icon icon="ep:folder" class="mr-5px" /> 批量修改分组
      </el-button>
    </div>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table row-key="id" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange">
      <el-table-column type="selection" width="35" />
      <el-table-column label="ID" align="center" prop="id" width="65px" />
      <!-- <el-table-column label="密钥ID" align="center" prop="keyId" /> -->
      <el-table-column label="设备名称" align="left" prop="deviceName" width="100px" />
      <!-- <el-table-column label="设备号" align="center" prop="deviceCode" /> -->
      <!-- <el-table-column label="MAC地址" align="center" prop="macAddress" /> -->
      <el-table-column label="IP地址" align="left" prop="ipAddress" width="150px" />
      <el-table-column label="所属用户" align="center" prop="userName">
        <template #default="scope">
          <span v-if="scope.row.userName">{{ scope.row.userName }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column label="所属分组" align="center" prop="groupName">
        <template #default="scope">
          <span v-if="scope.row.groupName">{{ scope.row.groupName }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="系统信息" align="center" prop="systemInfo" /> -->
      <!-- <el-table-column label="CPU信息" align="center" prop="cpuInfo" /> -->
      <!-- <el-table-column label="内存(MB)" align="center" prop="memorySize" /> -->
      <!-- <el-table-column label="硬盘(GB)" align="center" prop="diskSize" /> -->
      <el-table-column label="内存占用" width="100" align="center" prop="memoryUsage" >
          <template #default="scope">
            <el-progress :percentage="scope.row.memoryUsage" :format="percentFormat" />
          </template>
        </el-table-column>
      
      <el-table-column label="在线状态" align="center" prop="onlineStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.YK_DEVICE_ONLINE_STATE" :value="scope.row.onlineStatus" />
        </template>
      </el-table-column>
      <el-table-column label="客户端" align="center" prop="clientVersion" width="100px" />
      <el-table-column label="在线QQ" align="center" prop="onlineQQCount" width="80px" >
          <template #default="scope">
            <el-button type="text">{{ scope.row.onlineQQCount }}</el-button>
          </template>
        </el-table-column>
      <el-table-column label="群总数" prop="groupChatCount" align="center" width="80px" />
      <el-table-column label="最后心跳时间" align="center" prop="lastHeartbeatTime" :formatter="dateFormatter" width="170px" />
      <!-- <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.YK_DEVICE_STATE" :value="scope.row.status" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="170px" /> -->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" min-width="180px" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row.id)"
            v-hasPermi="['yunkong:device:update']">
            编辑
          </el-button>
          <el-button link type="primary" @click="() => openUpdateGroupDialog([scope.row.id])"
            v-hasPermi="['yunkong:device:update']">
            修改分组
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['yunkong:device:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <DeviceForm ref="formRef" @success="getList" />

  <!-- 添加设备弹窗 -->
  <el-dialog v-model="addDeviceDialogVisible" title="添加设备" width="500px" append-to-body>
    <el-form :model="addDeviceForm" ref="addDeviceFormRef" label-width="100px">
      <el-form-item label="生成数量" prop="count" :rules="[{ required: true, message: '请输入生成数量', trigger: 'blur' }]">
        <el-input-number v-model="addDeviceForm.count" :min="1" :max="100" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="addDeviceForm.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addDeviceDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleAddDevice" :loading="addDeviceLoading">确 定</el-button>
    </template>
  </el-dialog>

  <!-- 修改分组弹窗 -->
  <el-dialog v-model="updateGroupDialogVisible" title="修改分组" width="500px" append-to-body>
    <el-form :model="updateGroupForm" ref="updateGroupFormRef" label-width="100px">
      <el-form-item label="设备数量">
        <span>{{ updateGroupForm.ids.length }}</span>
      </el-form-item>
      <el-form-item label="选择分组" prop="groupId" :rules="[{ required: true, message: '请选择分组', trigger: 'change' }]">
        <el-select v-model="updateGroupForm.groupId" placeholder="请选择分组" clearable>
          <el-option v-for="group in groupList" :key="group.id" :label="group.groupName" :value="group.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateGroupDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleUpdateGroup" :loading="updateGroupLoading">确 定</el-button>
    </template>
  </el-dialog>

  <!-- 查看秘钥弹窗 -->
  <DeviceKeyList ref="deviceKeyListRef" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DeviceApi, Device, UpdateGroupReq } from '@/api/yunkong/device'
import { DeviceKeyApi } from '@/api/yunkong/devicekey'
import { DeviceGroupApi, DeviceGroup } from '@/api/yunkong/group'
import DeviceForm from './DeviceForm.vue'
import DeviceKeyList from './DeviceKeyList.vue'

/** 设备信息 列表 */
defineOptions({ name: 'Device' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Device[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 20,
  deviceName: undefined,
  ipAddress: undefined,
  memorySize: undefined,
  diskSize: undefined,
  onlineStatus: undefined,
  lastHeartbeatTime: [],
  status: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 添加设备相关
const addDeviceDialogVisible = ref(false)
const addDeviceLoading = ref(false)
const addDeviceForm = reactive({
  count: 1,
  remark: '批量生成'
})
const addDeviceFormRef = ref()

// 修改分组相关
const updateGroupDialogVisible = ref(false)
const updateGroupLoading = ref(false)
const updateGroupForm = reactive({
  ids: [] as number[],
  groupId: undefined as number | undefined
})
const updateGroupFormRef = ref()
const groupList = ref<DeviceGroup[]>([])

// 查看秘钥相关
const deviceKeyListRef = ref()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DeviceApi.getDevicePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 获取分组列表 */
const getGroupList = async () => {
  try {
    const data = await DeviceGroupApi.getDeviceGroupPage({ pageSize: 100 })
    groupList.value = data.list
  } catch (error) {
    console.error('获取分组列表失败', error)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 打开添加设备弹窗 */
const openAddDeviceDialog = () => {
  addDeviceDialogVisible.value = true
  addDeviceForm.count = 1
  addDeviceForm.remark = '批量生成'
}

/** 打开查看秘钥弹窗 */
const openViewKeysDialog = () => {
  deviceKeyListRef.value.open()
}

/** 打开修改分组弹窗 */
const openUpdateGroupDialog = async (ids?: number[]) => {
  // 如果传入了ids，则使用传入的，否则使用选中的
  updateGroupForm.ids = ids || checkedIds.value
  updateGroupForm.groupId = undefined
  
  // 获取分组列表
  await getGroupList()
  
  // 打开弹窗
  updateGroupDialogVisible.value = true
}

/** 百分比格式化 */
const percentFormat = (percentage) => {
  return `${percentage}%`
}

/** 添加设备操作 */
const handleAddDevice = async () => {
  try {
    await addDeviceFormRef.value.validate()
    addDeviceLoading.value = true
    await DeviceKeyApi.batchCreateDeviceKey({
      count: addDeviceForm.count,
      remark: addDeviceForm.remark
    })
    message.success('秘钥生成成功')
    addDeviceDialogVisible.value = false
    // 打开查看秘钥弹窗
    deviceKeyListRef.value.open()
  } catch (error) {
    console.error(error)
  } finally {
    addDeviceLoading.value = false
  }
}

/** 修改分组操作 */
const handleUpdateGroup = async () => {
  try {
    await updateGroupFormRef.value.validate()
    
    // 确保groupId有值
    if (!updateGroupForm.groupId) {
      message.warning('请选择分组')
      return
    }
    
    updateGroupLoading.value = true
    await DeviceApi.updateDeviceGroup({
      ids: updateGroupForm.ids,
      groupId: updateGroupForm.groupId
    })
    message.success('修改分组成功')
    updateGroupDialogVisible.value = false
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('修改分组失败', error)
  } finally {
    updateGroupLoading.value = false
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DeviceApi.deleteDevice(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 批量删除设备信息 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await DeviceApi.deleteDeviceList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch { }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Device[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DeviceApi.exportDevice(queryParams)
    download.excel(data, '设备信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>